<template>
	<div>
		<main-content
			v-if="!showDetail"
			:tableHeight.sync="tableHeight"
			:otherDependenComponents="otherDependenComponents"
		>
			<template slot="query">
				<el-form
					ref="form"
					:inline="true"
					:model="queryData"
					class="flex-warp-container"
				>
					<el-form-item
						:label="`${$t('common.belong_merchant')}:`"
						prop="merchantId"
						class="flex-row-container"
						label-width="77px"
					>
						<merchant-select
							v-model="queryData.merchantId"
						></merchant-select>
					</el-form-item>
					<el-form-item
						:label="`${$t('funds.apply_time')}:`"
						class="flex-row-container"
						label-width="77px"
					>
						<el-date-picker
							v-model="formTime.time"
							size="medium"
							:picker-options="pickerShortcut2"
							format="yyyy-MM-dd"
							type="daterange"
							range-separator="-"
							:start-placeholder="$t('common.start_date')"
							:end-placeholder="$t('common.end_date')"
							align="right"
							:clearable="false"
							:default-time="defaultTime"
						></el-date-picker>
					</el-form-item>
					<el-form-item
						:label="`${$t('funds.fund_audit.lock_status')}:`"
						class="flex-row-container"
						label-width="77px"
					>
						<el-select
							v-model="queryData.lockStatus"
							style="width: 180px"
							:popper-append-to-body="false"
							:placeholder="$t('common.select_all')"
							clearable
						>
							<el-option
								v-for="item in lockOrderType"
								:key="item.code"
								:label="item.description"
								:value="Number(item.code)"
							></el-option>
						</el-select>
					</el-form-item>
					<!-- <el-form-item label="调整类型:">
						<el-select
							v-model="queryData.adjustType"
							style="width: 180px"
							:popper-append-to-body="false"
						>
							<el-option :label="$t('common.all')" :value="0"></el-option>
							<el-option
								v-for="item in proxyPatchAddAdjustType"
								:key="item.code"
								:label="item.description"
								:value="Number(item.code)"
							></el-option>
						</el-select>
					</el-form-item> -->
					<el-form-item
						:label="`${$t('funds.order_no')}:`"
						class="flex-row-container"
						label-width="61px"
					>
						<el-input
							v-model="queryData.orderNo"
							clearable
							size="medium"
							style="width: 330px"
							:placeholder="$t('common.please_enter')"
							v-input="{ name: 'num_alp' }"
						></el-input>
					</el-form-item>
					<el-form-item
						:label="`总代账号:`"
						class="flex-row-container"
						label-width="77px"
					>
						<el-input
							v-model="queryData.proxyUsername"
							clearable
							size="medium"
							style="width: 200px"
							:placeholder="$t('common.please_enter')"
							v-input="{ name: 'num_alp' }"
						></el-input>
					</el-form-item>
					<el-form-item
						:label="`申请人:`"
						class="flex-row-container"
						label-width="77px"
					>
						<el-input
							v-model="queryData.applicantUsername"
							clearable
							size="medium"
							style="width: 200px"
							:placeholder="$t('common.please_enter')"
							v-input="{ name: 'num_alp' }"
						></el-input>
					</el-form-item>
					<!-- <el-form-item label="审核员:">
						<el-input
							v-model="queryData.lockAccount"
							clearable
							size="medium"
							style="width: 330px"
							:placeholder="$t('common.please_enter')"
							@keyup.enter.native="enterSearch"
						></el-input>
					</el-form-item> -->
					<el-form-item style="margin-left: 8px">
						<el-button
							type="primary"
							icon="el-icon-search"
							size="medium"
							@click="search"
						>
							{{ $t('common.search') }}
						</el-button>
						<el-button
							icon="el-icon-refresh-left"
							size="medium"
							@click="reset"
						>
							{{ $t('common.reset') }}
						</el-button>
						<!-- <el-button
							type="success"
							icon="el-icon-sort"
							:disabled="loading"
							size="medium"
							@click="openColSettings"
						>
							{{ $t('common.row_set') }}
						</el-button> -->
					</el-form-item>
				</el-form>
				<div class="divBox">
					<p class="danger data-refresh">
						{{ $t('funds.fund_audit.data_update_time') }}：
						{{ now }}
					</p>
					<el-select
						v-model="activeTopup"
						size="mini"
						:placeholder="$t('common.please_choose')"
						@change="recordTime"
					>
						<el-option
							v-for="item in timeList"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						></el-option>
					</el-select>
				</div>
			</template>
			<template slot="content">
				<div
					v-if="
						hasPermission('90930055') || hasPermission('90930056')
					"
				>
					<el-tabs v-model="activeName" @tab-click="handleClick">
						<el-tab-pane
							v-if="hasPermission('90930055')"
							:label="$t('funds.fund_audit.wait_audit_1')"
							name="0"
						></el-tab-pane>
						<el-tab-pane
							v-if="hasPermission('90930056')"
							:label="$t('funds.fund_audit.wait_audit_2')"
							name="1"
						></el-tab-pane>
					</el-tabs>
					<el-table
						v-loading="loading"
						element-loading-spinner="el-icon-loading"
						border
						size="mini"
						class="small-size-table"
						:data="dataList"
						style="width: 100%"
						highlight-current-row
						:header-cell-style="getRowClass"
						:max-height="tableHeight"
					>
						<el-table-column
							align="center"
							:label="$t('funds.fund_audit.lock')"
							min-width="60"
						>
							<template slot-scope="scope">
								<el-checkbox
									v-if="hasPermission('90930057')"
									v-model="scope.row.lockOrder"
									:disabled="!showLock(scope.row)"
									@change="lockChange(scope.row)"
								></el-checkbox>
								<span v-else>-</span>
							</template>
						</el-table-column>
						<el-table-column
							prop="auditStep"
							align="center"
							:label="$t('common.actions')"
							min-width="180"
						>
							<template slot-scope="scope">
								<el-button
									:class="
										(
											scope.row.lockBy !== name) ||
										!scope.row.lockBy
											? 'dis'
											: ''
									"
									type="primary"
									size="medium"
									@click="goDetail(scope.row)"
								>
									{{ $t('funds.fund_audit.audit') }}
								</el-button>
							</template>
						</el-table-column>

						<el-table-column
							prop="id"
							align="center"
							:label="$t('funds.order_no')"
							min-width="260"
							show-overflow-tooltip
						>
							<template slot-scope="scope">
								<Copy :title="scope.row.id" :copy="copy">
									{{ scope.row.id }}
								</Copy>
							</template>
						</el-table-column>
						<el-table-column
							prop="createdAt"
							align="center"
							:label="$t('funds.apply_time')"
							min-width="230"
							show-overflow-tooltip
						>
							<template slot-scope="scope">
								{{ scope.row.createdAt || '-' }}
							</template>
						</el-table-column>
						<el-table-column
							prop="realName"
							align="center"
							:label="$t('funds.fund_audit.operator')"
							min-width="180"
							show-overflow-tooltip
						>
							<template slot-scope="scope">
								{{ scope.row.createdBy || '-' }}
							</template>
						</el-table-column>
						<el-table-column
							prop="proxyUsername"
							align="center"
							:label="'总代账号'"
							min-width="180"
							show-overflow-tooltip
						>
							<template slot-scope="scope">
								<Copy
									:title="scope.row.proxyUsername"
									:copy="copy"
								>
									{{ scope.row.proxyUsername }}
								</Copy>
							</template>
						</el-table-column>
						<el-table-column
							prop="merchantName"
							align="center"
							:label="$t('common.belong_merchant')"
							min-width="150"
							show-overflow-tooltip
						>
							<template slot-scope="scope">
								{{ merchantFilter(scope.row.merchantId) }}
							</template>
						</el-table-column>

						<el-table-column
							prop="actAmount"
							align="center"
							:label="'实发分红'"
							min-width="200"
							show-overflow-tooltip
						>
							<template slot-scope="scope">
								<span
									v-if="
										!!scope.row.actAmount ||
											scope.row.actAmount === 0
									"
								>
									{{ handleCurrency('USDT') }}
									{{
										handleNumber(
											'USDT',
											scope.row.actAmount
										)
									}}
								</span>
							</template>
						</el-table-column>

						<el-table-column
							align="center"
							:label="$t('funds.fund_audit.audit_status')"
							min-width="180"
						>
							<!-- <template slot-scope="scope">
								<span
									:class="
										scope.row.lockStatus==1? 'lockingRgba'
											: 'disableRgba'
									"
								>
									{{ scope.row.lockStatus==1?'处理中':'待处理' }}
								</span>

							</template> -->
							<template slot-scope="scope">
								<span
									:class="
										Number(scope.row.lockStatus) === 1
											? 'lockingRgba'
											: 'deleteRgba'
									"
								>
									{{
										typeFilter(
											scope.row.lockStatus,
											'auditStatus'
										)
									}}
								</span>
							</template>
						</el-table-column>
						<el-table-column
							prop="lockAt"
							align="center"
							:label="$t('funds.fund_audit.lock_time')"
							min-width="220"
							show-overflow-tooltip
						>
							<template slot-scope="scope">
								<span v-if="!!scope.row.lockAt">
									{{ scope.row.lockAt }}
								</span>
								<span v-else>-</span>
							</template>
						</el-table-column>
						<el-table-column
							prop="lockAccount"
							align="center"
							:label="$t('funds.fund_audit.lock_account')"
							min-width="220"
							show-overflow-tooltip
						>
							<template slot-scope="scope">
								<div v-if="activeName === '0'">
									<span v-if="!!scope.row.firstAuditBy">
										{{ scope.row.firstAuditBy }}
									</span>
									<span v-else>-</span>
								</div>
								<div v-else>
									<span v-if="!!scope.row.secAuditBy">
										{{ scope.row.secAuditBy }}
									</span>
									<span v-else>-</span>
								</div>
							</template>
						</el-table-column>
					</el-table>
					<!-- 分页 -->
					<el-pagination
						v-if="
							hasPermission('90930055') ||
								hasPermission('90930056')
						"
						:current-page.sync="pageNum"
						class="pageValue"
						v-show="!!total"
						background
						layout="total, sizes,prev, pager, next, jumper"
						:page-size="pageSize"
						:page-sizes="pageSizes"
						:total="total"
						:pager-count="9"
						@current-change="handleCurrentChange"
						@size-change="handleSizeChange"
					></el-pagination>
				</div>
				<el-empty
					v-else
					:description="$t('funds.jurisdiction_tip')"
				></el-empty>
			</template>
		</main-content>
		<detail
			v-else
			:type="type"
			:rowData="rowData"
			:activeName="activeName"
			@goBack="goBack"
		></detail>
		<el-dialog
			:title="$t('common.row_set')"
			center
			:visible.sync="colSettings.visible"
			width="475px"
			class="setting-div"
		>
			<div>
				<el-link type="primary" class="mb15" @click="clickDel">
					复原缺省
				</el-link>
			</div>
			<div
				v-for="(value, name1) in activityListField"
				:key="name1"
				class="setting-div"
			>
				<el-checkbox v-model="dialogColumnData[name1]">
					{{ name1 }}
				</el-checkbox>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="colSettings.visible = false">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button type="primary" @click="handleOrderList">
					{{ $t('common.submit') }}
				</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
import { getUsername, getUserInfo } from '@/utils/auth'
import { routerNames } from '@/utils/consts'
import MainContent from '@/components/MainContent/index.vue'

const end = () => {
	return dayjs()
		.endOf('day')
		.valueOf()
}
const start = () => {
	return dayjs()
		.startOf('day')
		.valueOf()
}
export default {
	name: routerNames.agentTopupReview,
	components: {
		detail: () => import('./components/detail'),
		MainContent
	},
	mixins: [list],
	data() {
		// this.loadData = this.throttle(this.loadData, 1000)
		return {
			tableHeight: 480,
			otherDependenComponents: ['reviewTab'],
			queryData: {
				lockStatus: '',

				orderNo: ''
			},
			type: true,
			showDetail: false,
			formTime: {
				time: [start(), end()]
			},
			rowData: {},
			now: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
			name: '',
			activeName: '-1',
			dataList: [],
			timeList: [],
			agentTopupTimer: null,
			activeTopup: this.$t('funds.fund_audit.no_reload'),
			userInfo: {},
			colSettings: {
				visible: false,
				dialogColumnData: {}
			},
			activityListField: {
				// 锁单: true,
				// 订单号: true,
				// 申请时间: true,
				// 申请人: true,
				// 代理账号: true,
				// 所属商户: true,
				// 调整类型: true,
				// 申请金额: true,
				// 审核状态: true,
				// 锁单状态: true,
				// 审核人: true
				[this.$t('funds.fund_audit.lock')]: true,
				[this.$t('funds.order_no')]: true,
				[this.$t('funds.apply_time')]: true,
				[this.$t('funds.fund_audit.operator')]: true,
				[this.$t('funds.proxy_name')]: true,
				[this.$t('common.belong_merchant')]: true,
				[this.$t('funds.fund_audit.adjust_type')]: true,
				[this.$t('funds.fund_audit.order_amount')]: true,
				[this.$t('funds.fund_audit.audit_status')]: true,
				[this.$t('funds.fund_audit.lock_time')]: true,
				[this.$t('funds.fund_audit.lock_account')]: true
			}
		}
	},
	computed: {
		lockOrderType() {
			return this.globalDics.lockStatus || []
		},
		proxyPatchAddAdjustType() {
			return this.globalDics.proxyPatchAddAdjustType || []
		}
	},
	created() {
		this.initIndexDB('agentTopupReview', this.activityListField)
		if (this.hasPermission('90930055') || this.hasPermission('90930056')) {
			this.getKvconfigList()
		}
	},
	mounted() {
		if (this.hasPermission('90930055')) {
			this.activeName = '0'
		} else if (this.hasPermission('90930056')) {
			this.activeName = '1'
		} else {
			this.activeName = '-1'
		}
		this.name = getUsername()
		this.userInfo = getUserInfo()
		this.loadData()
	},
	activated() {
		if (
			Number(this.activeTopup) &&
			(this.hasPermission('90930055') || this.hasPermission('90930056'))
		) {
			this.agentTopupTimer = setInterval(
				this.loadData,
				this.activeTopup * 1000
			)
		} else {
			clearInterval(this.agentTopupTimer)
		}
	},
	deactivated() {
		clearInterval(this.agentTopupTimer)
	},
	beforeDestroy() {
		clearInterval(this.agentTopupTimer)
		this.agentTopupTimer = null
	},
	methods: {
		search() {
			this.pageNum = 1
			clearInterval(this.agentTopupTimer)
			this.agentTopupTimer = null
			if (Number(this.activeTopup)) {
				this.agentTopupTimer = setInterval(
					this.loadData,
					this.activeTopup * 1000
				)
			}
			this.loadData()
		},
		recordTime(val) {
			this.activeTopup = val
			if (Number(val)) {
				clearInterval(this.agentTopupTimer)
				this.agentTopupTimer = setInterval(this.loadData, val * 1000)
			} else {
				clearInterval(this.agentTopupTimer)
			}
		},
		showLock(rowData) {
			return (

				(this.name === rowData.lockBy) ||
				!rowData.lockBy
			)
		},
		getKvconfigList() {
			this.timeList = []
			let str = ''
			let arr = []
			const params = {
				k: 'funds.audit.pagerefresh.interval.config',
				pageNum: 1,
				pageSize: 10
			}
			this.$api.getkvconfigQueryList(params).then((res) => {
				if (res.code === 200 && res.data) {
					const val = res.data.records[0] || []
					if (val.v) {
						str = val.v
						arr = str.split(',').sort()
						arr.forEach((item, index) => {
							const obj = {}
							if (Number(item) === 0) {
								obj.label = this.$t(
									'funds.fund_audit.no_reload'
								)
								obj.value = this.$t(
									'funds.fund_audit.no_reload'
								)
								this.timeList.push(obj)
								this.activeTopup = this.$t(
									'funds.fund_audit.no_reload'
								)
								this.agentTopupTimer = null
							} else if (Number(item)) {
								obj.label =
									item + this.$t('funds.fund_audit.second')
								obj.value = item
								this.timeList.push(obj)
							}
							// if (Number(item) && index === 1) {
							// 	this.activeTopup = item
							// 	this.agentTopupTimer = setInterval(this.loadData, item * 1000)
							// }
						})
					}
				}
			})
		},
		handleClick() {
			this.pageNum = 1
			this.search()
		},
		loadData() {
			const [startTime, endTime] = this.formTime.time || []
			let params = {
				...this.queryData,
				auditStep: this.activeName === '0' ? 1 : 2,
				startDate: startTime
					? dayjs(startTime).format('YYYY-MM-DD')
					: undefined,
				endDate: endTime
					? dayjs(endTime).format('YYYY-MM-DD')
					: undefined
			}

			params = {
				...this.getParams(params)
			}

			// let type = ''
			// if (this.activeName === '0') {
			// 	type = 'firstAuditAddAuditProxy'
			// } else if (this.activeName === '1') {
			// 	type = 'secondAddAuditProxy'
			// }
			if (this.activeName === '-1') {
				return
			} else {
				this.loading = true
				this.$api
					.pageDividendRecordPage(params)
					.then((res) => {
						if (res.code === 200) {
							this.now = dayjs(new Date()).format(
								'YYYY-MM-DD HH:mm:ss'
							)
							const { record, totalRecord } = res.data || {}
							this.dataList = record || []
							this.total = totalRecord || 0
							if (this.dataList) {
								this.dataList.forEach((item) => {
									item.lockOrder =
										Number(item.lockStatus) === 1
								})
							}
							this.loading = false
						} else {
							this.loading = false
							this.$message({
								message: res.msg,
								type: 'error'
							})
						}
					})
					.catch(() => {
						this.loading = false
					})
			}
		},
		isMyAudit(rowData) {
			return rowData.lockStatus === 1 && this.name === rowData.lockBy
		},
		goDetail(row) {
			// this.type =
			// 	(!!row.lockAccountId &&
			// 		this.userInfo.id === +row.lockAccountId) ||
			// 	(!row.lockAccountId && this.name === row.lockAccount)
			this.type = this.isMyAudit(row)
			this.rowData = row
			this.showDetail = true
		},
		goBack() {
			this.showDetail = false
			this.loadData()
			// this.dataList = []
			// this.search()
		},
		reset() {
			this.queryData = {
				lockOrder: '',
				orderNo: ''
			}
			this.formTime = {
				time: [start(), end()]
			}
			this.search()
		},
		reloadTime() {
			this.formTime = {
				time: [start(), end()]
			}
		},
		handleCurrentChange(val) {
			this.pageNum = val
			clearInterval(this.agentTopupTimer)
			this.agentTopupTimer = null
			if (Number(this.activeTopup)) {
				this.agentTopupTimer = setInterval(
					this.loadData,
					this.activeTopup * 1000
				)
			}
			this.loadData()
		},
		handleSizeChange(val) {
			this.pageSize = val
			clearInterval(this.agentTopupTimer)
			this.agentTopupTimer = null
			if (Number(this.activeTopup)) {
				this.agentTopupTimer = setInterval(
					this.loadData,
					this.activeTopup * 1000
				)
			}
			this.loadData()
		},
		lockChange(val) {
			const loading = this.$loading({
				lock: true,
				text: 'Loading',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			})
			/**
			 *  审核单ID(18) - id
			 *  锁单状态 - lockStatus
			 *  商户ID(18) - merchantId
			 */
			this.$api
				.batchClock({
					orderId: val.id,
					lockStatus: Number(val.lockStatus) === 1 ? 0 : 1
					// merchantId: val.merchantId
				})
				.then((res) => {
					if (res?.code === 200) {
						loading.close()
						this.$message({
							type: 'success',
							message: this.$t('common.action_success')
						})
						this.search()
					} else {
						loading.close()
						this.$message({
							message: res?.msg,
							type: 'error'
						})
					}
				})
				.catch(() => {
					loading.close()
					val.lockOrder = false
				})
		},
		// 提交列设置数据
		handleOrderList() {
			this.colSettings.visible = false
			this.updateIndexDB()
		},
		// 打开列设置弹框
		openColSettings() {
			this.getIndexDB(this.activityListField)
			this.colSettings.visible = true
		},
		clickDel() {
			this.dialogColumnData = {}
			this.dialogColumnData = {
				// 锁单: true,
				// 订单号: true,
				// 申请时间: true,
				// 申请人: true,
				// 代理账号: true,
				// 所属商户: true,
				// 调整类型: true,
				// 申请金额: true,
				// 审核状态: true,
				// 锁单状态: true,
				// 审核人: true
				[this.$t('funds.fund_audit.lock')]: true,
				[this.$t('funds.order_no')]: true,
				[this.$t('funds.apply_time')]: true,
				[this.$t('funds.fund_audit.operator')]: true,
				[this.$t('funds.proxy_name')]: true,
				[this.$t('common.belong_merchant')]: true,
				[this.$t('funds.fund_audit.adjust_type')]: true,
				[this.$t('funds.fund_audit.order_amount')]: true,
				[this.$t('funds.fund_audit.audit_status')]: true,
				[this.$t('funds.fund_audit.lock_time')]: true,
				[this.$t('funds.fund_audit.lock_account')]: true
			}
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
	text-align: center;
	color: #909399;
	font-weight: 700;
}
::v-deep .caret-wrapper {
	position: absolute;
	top: 50%;
	transform: translateY(-50%);
}
.divBox {
	display: flex;
	.el-select {
		width: 100px;
	}
}
.data-refresh {
	margin-top: 0;
	padding-bottom: 20px;
	line-height: 28px;
	margin-right: 20px;
}
</style>
